package com.sydata.service;


import com.jcraft.jsch.*;
import com.sydata.config.SftpConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;


/**
 * 连接sftp 类
 *
 * @author huangzj@uhuibao.com
 */
@Service
public class SftpService {

    public static Logger logger = LoggerFactory.getLogger(SftpService.class);

    private final SftpConfig sftpConfig;

    public SftpService(SftpConfig sftpConfig) {
        this.sftpConfig = sftpConfig;
    }

    /**
     * 通过传递日期 读取服务器最新一个文件
     * 如：CDR_IIJ_LinksField_20231119000000000_6affd591-5db3-482d-bf32-8e158a6221d5.csv
     *
     * @param fileDate
     * @return
     */
    public List<String> connAndReadLinesFromFile(String fileDate) {
        List<String> lines = new ArrayList<>();

        JSch jsch = new JSch();
        Session session = null;
        ChannelSftp channelSftp = null;

        try {
            jsch.addIdentity(sftpConfig.getPrivateKey());
            session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getHost(), sftpConfig.getPort());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();


            String fileDirectory = "/upload";
            String fileNamePattern = "CDR_IIJ_LinksField_" + fileDate;
            String latestFile = getLatestFile(channelSftp, fileDirectory, fileNamePattern);
            if (latestFile != null) {
                logger.info("获取文件:"+latestFile);
                lines = readLinesFromFile(channelSftp, fileDirectory + "/" + latestFile);

            } else {
                logger.info("获取文件:"+ "No matching file found.");
            }

            channelSftp.disconnect();
            session.disconnect();

        } catch (JSchException | SftpException e) {
            e.printStackTrace();

        } finally {
            // 省略关闭资源的代码
        }

        return lines;
    }

    private static List<String> readLinesFromFile(ChannelSftp channelSftp, String filePath) throws SftpException {
        List<String> lines = new ArrayList<>();

        try (InputStream inputStream = channelSftp.get(filePath);
             InputStreamReader reader = new InputStreamReader(inputStream);
             CSVParser csvParser = CSVFormat.DEFAULT.parse(reader)) {
            for (CSVRecord record : csvParser) {
                String line = String.join(",", record) + ","+filePath;
                lines.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return lines;
    }


    /**
     * 匹配文件格式 获取最新的文件
     *
     * @param channelSftp
     * @param directory
     * @param filenamePattern
     * @return
     * @throws SftpException
     */
    private static String getLatestFile(ChannelSftp channelSftp, String directory, String filenamePattern)
            throws SftpException {
        channelSftp.cd(directory);

        Vector<ChannelSftp.LsEntry> files = channelSftp.ls(".");
        String latestFile = null;
        long latestTimestamp = 0;

        for (ChannelSftp.LsEntry entry : files) {
            if (!entry.getAttrs().isDir()) {
                String filename = entry.getFilename();
                if (filename.startsWith(filenamePattern)) {
                    SftpATTRS attrs = entry.getAttrs();
                    long timestamp = attrs.getMTime();
                    if (timestamp > latestTimestamp) {
                        latestFile = filename;
                        latestTimestamp = timestamp;
                    }
                }
            }
        }

        return latestFile;
    }
}
